// pages/book/book-detail/index.js
let deskid = ''  //记录书桌id
Page({

    /**
     * 页面的初始数据
     */
    data: {
        idx:0,
        catalog:[],
        isdesk:false    //标志当前图书，是否被加入了书桌
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.getStorage({
            key:'bookdetail',
            success:(res)=>{
                console.log(res);
                this.setData(res.data)
                let uuid = res.data.sourceUrl.split('/source/')[1]
                this.getCatelog(uuid)
                // 判断当前用户有没有收藏这本书
                let {userInfo} = getApp()
                if(!userInfo){return}
                let userid = userInfo.objectId
                let bookid = res.data.objectId
                let url = `/1.1/classes/Desk?where={"userid":"${userid}","bookid":"${bookid}"}` //用图书id、用户id，查询书桌表
                getApp().$get(url).then(desk=>{
                    console.log(desk);
                    if(desk.data.results.length){
                        this.setData({isdesk:true})
                        deskid = desk.data.results[0].objectId
                    }
                })
            }
        })
    },
    getCatelog(uuid){ //获取目录
        let url = `https://m.yuedu.163.com/reader/book/info.json?source_uuid=${uuid}&catalog_only=true`
        wx.request({
          url,
          method:'get',
          success:(res)=>{
              console.log(res);
              let {catalog} = res.data.data
              this.setData({catalog})
          }
        })
    },
    handleTab(ev){
        console.log(ev);
        let {index} = ev.detail
        this.setData({idx:index})
    },
    handleDesk(){ //加入书桌
        let {userInfo} = getApp()
        if(!userInfo){
            wx.navigateTo({
              url: '/pages/login/index',
            })
            return
        }
        let userid = userInfo.objectId //用户id
        let bookid = this.data.objectId //图书id
        let {title,iconUrl,author} = this.data
        getApp().$post('/1.1/classes/Desk',{ //加入书桌
            userid,bookid,title,iconUrl,author
        }).then(res=>{
            console.log(res);  //这个res中会有书桌objectId
            this.setData({isdesk:true})
            deskid = res.data.objectId
            wx.showToast({
              title: '成功加入书桌',
              icon:'none'
            })
        })
    },
    handleDelDesk(){ //移除书桌
        console.log('被移除的书桌id',deskid);
        getApp().$del(`/1.1/classes/Desk/${deskid}`).then(res=>{
            console.log(res);
            this.setData({isdesk:false})
            deskid = ''
            wx.showToast({
                title: '成功移出书桌',
                icon:'none'
              })
        })
    }

})